<template>
  <div class="page-back">
    <page-background></page-background>
    <page-top win="mainWindow"></page-top>
    <input type="file" id="file" @change="uploadFile" v-show="false"/>
    <input type="file" multiple id="files" @change="uploadFiles" v-show="false"/>
    <div class="page-body" :class="{'page-body-full':!sysStores.isWindows}">
      <!--没有登录的情况需要提示用户进行登录-->
      <div class="welcome" v-if="!sysStores.loginState">
        <div class="tit">
          <div class="c1">政务视频远程服务助手</div>
          <div class="c2">我们将通过视频的形式,为您提供事项咨询、材料帮看、远程帮办服务</div>
          <div class="c2">视频连接成功后，将有坐席工作人员为您提供远程面对面服务！</div>
        </div>
        <div class="no-login">
          <q-btn class="btn-login" size="lg" color="white" text-color="black" @click="toLogin" label="前 往 登 录"/>
          <div class="tis">您当前尚未登录，请先进行登录</div>
        </div>
      </div>
      <!--已经登录，判断登录账号的角色进入不同角色的主页-->
      <template v-else>
        <worker-index v-if="sysStores.userInfo.role_id == 4 || sysStores.userInfo.role_id == 5"></worker-index>
        <crowd-index v-if="sysStores.userInfo.role_id == 1"></crowd-index>
      </template>
    </div>
  </div>
</template>

<script setup lang="ts">
import {onMounted, ref, watch} from "vue";
import {useSysStore} from "stores/sysStore";
import PageTop from "components/page-top.vue";
import {useRouter} from "vue-router";
import PageBackground from "components/page-background.vue";
import WorkerIndex from "pages/components/workerIndex.vue";
import CrowdIndex from "pages/components/crowdIndex.vue";
import APIClient from "src/utils/APIClient";
import eventBus from "src/utils/eventBus";
import Routes from "src/router/routes";
import {Wss} from "src/utils/type";
import {uploadFileToService,uploadFilesToService} from "src/utils/util";
import {useQuasar} from "quasar";

/**
 * 项目说明：
 * 1，采用Quasar框架的spa和electron能力，UI采用quasar自带的样式渲染，文档：https://adwinyang.github.io/quasar-doc-zh-cn/
 * 2，通过indexPage进行登录验证和分流，每次进入利用userInfo接口进行登录验证和获取用户信息，以及建立wss连接
 * 3，为优化代码可读性便于维护，本项目分为群众端和坐席端，work开头全为坐席相关代码，反之people亦然
 * 4，根目录component中存放全局复用组件，page的component放置部分页面组件
 * 5，请注意群众端会有electron和web两种场景，在用到electronAPI的时候需要兼容
 * 6，图标库采用阿里巴巴的iconfont，如有添加请联系管理员添加权限
 */

let sysStores = useSysStore();
let router = useRouter();
let $q = useQuasar()

onMounted(async () => {
  //判断是web环境还是windows环境
  sysStores.isWindows = !!window.ipcChannel;
  //如果是从agent跳转过来的，直接进行登录验证
  let href = window.location.href;
   if(href.indexOf('token')!=-1){
     // let token = href.substring(href.lastIndexOf('token')+6)
     const {token,districts} = getTokenAndDistricts(href)
     localStorage.setItem('token',(token) as string);
     localStorage.setItem('districts',(districts) as string);
     if (districts == '510600000000') {
       sysStores.fromAgent = true;
     } else {
       $q.notify({
          type: 'negative',
          message: '当前坐席忙',
          timeout: 2000
       })
     }
   }
  //验证用户是否登录，或验证登录是否过期
  checkLoginAndGetUserinfo();
});

function getTokenAndDistricts(url,key) {
  try {
    // 把 hash（#）后的部分当成查询字符串处理
    const queryString = url.split('#')[1]?.split('?')[1];
    if (!queryString) return null;

    const params = new URLSearchParams(queryString);

    return {
      token: params.get('token') || null,
      districts: params.get('districts') || null
    };
  } catch (e) {
    console.error('解析URL出错:', e);
    return null;
  }
}



watch(()=>sysStores.wssMessage,(newVal)=>{
  let msg:Wss = (newVal as Wss);
  //连接内部关闭
  if (msg.message_type == 'close')
    return console.error(msg);
},{
  deep: true,
})

//登录失效的时候触发页面变化
eventBus.$on('loginExpire',()=>{
  sysStores.loginState = false;
})

//上传文件时候触发。发出出去
const uploadFile = async () => {
  let notif = $q.notify({
    type: 'ongoing',
    message: '请稍等正在上传中...'
  })
  await uploadFileToService()
  notif({
    type: 'positive',
    message: '上传完成！',
    timeout: 1000
  })
}

const uploadFiles = async () => {
  let notif = $q.notify({
    type: 'ongoing',
    message: '请稍等正在上传中...'
  })
  await uploadFilesToService()
  notif({
    type: 'positive',
    message: '上传完成！',
    timeout: 1000
  })
}

//每次进入页面都要校验登录是否过期
const checkLoginAndGetUserinfo = () => {
  APIClient.get('/user/info').then(res=>{
    if (!res) return;
    sysStores.connectWss(); //创建wss连接
    sysStores.userInfo = res?.data
    localStorage.setItem("userInfo", JSON.stringify(res?.data));
    localStorage.setItem("userId", res?.data.id);
    sysStores.loginState = true;
    getAliConfig();
  })
}
// 获取阿里云的配置，存储到store中，用于RTM中的实时语音转写
const getAliConfig = () => {
  APIClient.get('/user/stt/token').then(res=>{
    sysStores.aliConfig = {
      appkey:res?.data.AppKey,
      token:res?.data.AliToken,
    };
  })
}
//前往登录
const toLogin = () => {
  router.push('/login')
}

// 监听页面卸载事件
window.addEventListener('unload', () => {
  // 执行清理操作（同步）
  localStorage.setItem('lastLeaveTime', Date.now());
  // 发送用户离开日志（异步，但可能不保证完成）
  eventBus.$emit('unloadPage')
});

// window.addEventListener('beforeunload', function (event) {
//   const confirmationMessage = "确定要离开此页面吗？";
//   event.returnValue = confirmationMessage;
//   return confirmationMessage;
// });
</script>

<style scoped lang="scss">
.page-back {
  overflow: hidden;
  width: 100wh;
  height: 100vh;
  // background-image: linear-gradient(to top, #e6e9f0 0%, #eef1f5 100%);
  position: relative;

  //.page-body-full {
  //  height: 100% !important;
  //}

  .page-body {
    width: 100%;
    height: calc(100% - 60px);
    display: flex;
    justify-content: center;
    align-items: center;
    position: relative;
    z-index: 1000;

    .welcome {
      color: #fff;
      .tit {
        padding-bottom: 20px;

        .c1 {
          font-size: 30px;
          font-weight: bold;
        }

        .c2 {
          padding-top: 10px;
          color: #f0f0f0;
          font-size: 16px;
        }
      }

      .no-login {
        .tis {
          padding-top: 20px;
          font-size: 16px;
        }
        .btn-login{
          color:  #689FF2 !important
        }
      }
    }
  }
}
</style>
